﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using ePlanet.SingleWell.Models;
using ePlanet.SingleWell.Services;
using ePlanet.ResourceRequest.DataAccess;
using ePlanet.ResourceRequest.Models;
using ePlanet.ResourceRequest.Services;
using System.Data;

namespace Web.Views.ResourceRequestManage
{
    public partial class ResourceRequestExam : PageBase
    {
        [Dependency]
        public IResourceRequestService m_IResourceRequestService
        {
            get;
            set;
        }

        [Dependency]
        public ISingleWellService m_ISingleWellService
        {
            get;
            set;
        }

        [Dependency]
        public IAttachmentService m_IAttachmentService
        {
            get;
            set;
        }

        
        private ResourceRequestModel m_ResourceRequestModel
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                {
                    return  this.m_IResourceRequestService.GetResourceRequestModelByID(Request.QueryString["ID"]);
                }
                else
                {
                    return null;
                }
            }
        }

        private Web.SystemLogin.Models.User m_CurrentUser
        {
            get
            {
                return (Web.SystemLogin.Models.User)Session["CurrentUser"];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                
                if (!IsPostBack)
                {
                    string urlReferrer = Request.UrlReferrer.ToString();
                    urlReferrer = urlReferrer.Substring(urlReferrer.LastIndexOfAny(new char[] { '/' }) + 1);
                    ViewState["ResourceRequestExam"] = urlReferrer;

                    ResourceRequestModel model = this.m_ResourceRequestModel;
                    if (model != null)
                    {
                        this.BindData(model);

                    }
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        protected void btnAgreeNewRequest_Click(object sender, EventArgs e)
        {
            try
            {
                ResourceRequestModel model = this.CollectModel();
                if (model != null)
                {
                    this.Agree(model);
                    //Alert("同意申请成功");
                    Response.Redirect(ViewState["ResourceRequestExam"].ToString());
                }
                else
                {
                    throw new Exception("所获取的资源申请对象为空");
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        protected void btnDisAgreeNewRequest_Click(object sender, EventArgs e)
        {
            try
            {
                ResourceRequestModel model = this.CollectModel();
                if (model != null)
                {
                    this.DisAgree(model);
                    Response.Redirect(ViewState["ResourceRequestExam"].ToString());
                    //Alert("不同意申请成功");
                }
                else
                {
                    throw new Exception("所获取的资源申请对象为空");
                }
            }
            catch (Exception ex)
            {
                Alert(ex.Message);
            }
        }

        #region  私有方法

        private void BindData(ResourceRequestModel model)
        {
            ResourceRequestModel.RESOURCEREQUESTRow oRESOURCEREQUESTRow = model.RESOURCEREQUEST[0];
            SingleWellModel oSingleWellModel = this.m_ISingleWellService.GetSingleWellModel(oRESOURCEREQUESTRow.WELLDATAID);
            if (oSingleWellModel != null && oSingleWellModel.SINGLEWELL.Count > 0)
            {
                this.CurrentPageState = PageState.State_Edit;
                //绑定数据
                SingleWellModel.SINGLEWELLRow row = oSingleWellModel.SINGLEWELL[0];
                if (!row.IsA0Null())
                {
                    this.txtA0.Text = row.A0.ToString();
                }
                if (!row.IsA3Null())
                {
                    this.txtA3.Text = row.A3.ToString();
                }
                if (!row.IsA4Null())
                {
                    this.txtA4.Text = row.A4.ToString();
                }
                
                if (!row.IsBEGINDATENull())
                {
                    this.txtBEGINDATE.Text = row.BEGINDATE.ToShortDateString();
                }
                if (!row.IsBEGINWORKDATENull())
                {
                    this.txtBeginWorkDate.Text = row.BEGINWORKDATE.ToShortDateString();
                }
                if (!row.IsDATAFILENAMENull())
                {
                    this.txtDatafileName.Text = row.DATAFILENAME;
                }
                if (!row.IsFINISHDATENull())
                {
                    this.txtFINISHDATE.Text = row.FINISHDATE.ToShortDateString();
                }
                if (!row.IsFINISHWORKDATENull())
                {
                    this.txtFinishWorkDate.Text = row.FINISHWORKDATE.ToShortDateString();
                }
                
                if (!row.IsWELLDEPTHNull())
                {
                    this.txtWellDepth.Text = row.WELLDEPTH.ToString();
                }
                if (!row.IsWELLTYPENull())
                {
                    this.txtWellType.Text = row.WELLTYPE;
                }

                if (!oRESOURCEREQUESTRow.IsCANDOWNLOADNull())
                {
                    this.cbCanDownload.Checked = oRESOURCEREQUESTRow.CANDOWNLOAD == 1 ? true : false;
                }

                if (!oRESOURCEREQUESTRow.IsCANVIEWNull())
                {
                    this.cbCanView.Checked = oRESOURCEREQUESTRow.CANVIEW == 1 ? true : false;
                }

                if (oRESOURCEREQUESTRow.VALIDPERIOD > DateTime.Parse("2012-1-1"))
                {
                    this.txtValidPeriod.Text = oRESOURCEREQUESTRow.VALIDPERIOD.ToShortDateString();
                }

                //added by jiejiep
                //时间：2013年4月3日 18:30:36
                if (!row.IsWORKMODENull())
                {
                    this.txtWorkMode.Text = row.WORKMODE;
                }
                this.txtWellCode.Text = row.WELLCODE ?? "";


                this.BindWellDetail(oSingleWellModel);
                this.BindAttachment(oSingleWellModel);
            }
        }

        private ResourceRequestModel CollectModel()
        {
            ResourceRequestModel rtnModel = null;
            ResourceRequestModel tempModel = this.m_ResourceRequestModel;

            if (tempModel != null)
            {
                if (!string.IsNullOrEmpty(this.txtValidPeriod.Text.Trim()))
                {
                    DateTime validPeriod = DateTime.MinValue;
                    if (DateTime.TryParse(this.txtValidPeriod.Text.Trim(), out validPeriod))
                    {
                        if (validPeriod <= DateTime.Now.Date)
                        {
                            throw new Exception("选择的日期必须大于当前日期");
                        }
                        rtnModel = new ResourceRequestModel();
                        ResourceRequestModel.RESOURCEREQUESTRow row = rtnModel.RESOURCEREQUEST.NewRESOURCEREQUESTRow();

                        ResourceRequestModel.RESOURCEREQUESTRow originalRow = tempModel.RESOURCEREQUEST[0];
                        row.TEMPUSERID = originalRow.TEMPUSERID;
                        row.WELLDATAID = originalRow.WELLDATAID;
                        row.STATUSID = (int)ResourceRequestEnum.AgreeView;
                        row.ID = originalRow.ID;
                        row.VALIDPERIOD = validPeriod;
                        row.CANDOWNLOAD = this.cbCanDownload.Checked == true ? 1 : 0;
                        row.CANVIEW = this.cbCanView.Checked == true ? 1 : 0;
                        row.COMMENTMESSAGE = this.txtComment.Text.Trim();

                        rtnModel.RESOURCEREQUEST.AddRESOURCEREQUESTRow(row);
                        if (this.CurrentPageState == PageState.State_Edit)
                        {
                            row.AcceptChanges();
                            row.SetModified();
                        }
                    }
                    else
                    {
                        throw new Exception("过期日期不是时间格式");
                    }
                }
                else
                {
                    throw new Exception("过期日期不是时间格式");
                }
            }
            return rtnModel;
        }

        private void Agree(ResourceRequestModel model)
        {
            this.m_IResourceRequestService.AgreeRequest(model);
        }

        private void DisAgree(ResourceRequestModel model)
        {
            this.m_IResourceRequestService.DisAgreeRequest(model);
        }

        #endregion

        #region 私有方法
        private void BindAttachment(SingleWellModel oModel)
        {
            DataTable oDataTable = null;
            this.m_IAttachmentService.Initialize("SingleWell");
            List<AttachmentModel> modelList = this.m_IAttachmentService.GetAttachmentModelByObjectID(oModel.SINGLEWELL[0].DATAID);
            if (modelList != null && modelList.Count > 0)
            {
                oDataTable = new DataTable();
                oDataTable.Columns.Add("attachmentid");
                oDataTable.Columns.Add("attachmentname");
                oDataTable.Columns.Add("uploadtime");
                oDataTable.Columns.Add("attachmentsize");

                foreach (AttachmentModel model in modelList)
                {
                    DataRow dr = oDataTable.NewRow();
                    dr["attachmentid"] = model.AttachmentID;
                    dr["attachmentname"] = model.AttachmentName;
                    dr["uploadtime"] = model.UpdateTime;
                    dr["attachmentsize"] = (model.AttachmentSize / (1000 * 1000) > 0) ? (Math.Round((float)model.AttachmentSize / (1000 * 1000), 3) + "MB") : Math.Round((float)model.AttachmentSize / (1000)) + "KB";

                    oDataTable.Rows.Add(dr);
                }
                //时间：2013年3月24日 12:45:51
                //added by jiejiep
                //绑定附件
                gv_AttachMent.DataSource = oDataTable;
                gv_AttachMent.DataBind();
            }
        }

        protected void gv_AttachMent_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRow row = ((DataRowView)e.Row.DataItem).Row;
                e.Row.Cells[0].Text = string.Format("<a target='_blank' href='../../WebDoc/WebDoc.aspx?AttachmentID={0}&AttachmentDBHelperString=SingleWell'>{1}</a>", 
                    row["attachmentid"], row["attachmentname"]);
            }
        }

        private bool BindWellDetail(SingleWellModel oModel)
        {
            try
            {
                DataTable oDataTable = oModel.WELLDATADETAIL as DataTable;
                this.gv_SingleWellDetail.DataSource = oDataTable;
                this.gv_SingleWellDetail.DataBind();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        
        #endregion
    }
}